package com.myapp.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myapp.api.entity.Dept;
import com.myapp.api.service.DeptService;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.ResultStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Api(value = "DeptController",description = "dept 表的相关 CURD 操作")
@RestController
@RequestMapping(value = "/dept", produces = "application/json;charset=UTF-8")
public class DeptController {
    @Autowired
    private DeptService service;

    @ApiOperation(value="获取院系信息列表",notes="获取所有的院系信息",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/all")
    public ResponseEntity<?> getDepts(@RequestParam(required = true, defaultValue = "1") Integer pageNum, @RequestParam(required = true, defaultValue = "15") Integer pageSize) {
        String orderBy = "CreateTime DESC";
        PageHelper.startPage(pageNum, pageSize, orderBy);
        List<Dept> dept = service.getDepts();

        HttpStatus status = HttpStatus.OK;
        PageInfo<Dept> records = new PageInfo<>(dept);
        return new ResponseEntity<PageInfo<Dept>>(records, status);
    }

    @ApiOperation(value="获取院系详细信息",notes="根据 url 的院系编号来获取详细信息",produces = "application/json")
    @ApiImplicitParam(name = "did", value = "院系编号", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/{did}")
    public ResponseEntity<?> getDeptByDid(@PathVariable(value = "did") String did) {
        if (!did.equals(0)) {
            Dept record = service.getDeptByDid(did);

            HttpStatus status = HttpStatus.OK;
            Object obj = new Object();
            if (record == null)
                return new ResponseEntity<Object>(obj, status);
            else
                return new ResponseEntity<Dept>(record, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="根据院系名查询课程信息",notes="通过模糊匹配院系名",produces = "application/json")
//    @ApiImplicitParams({
    @ApiImplicitParam(name = "dname", value = "院系名关键词", required = true, dataType = "String", paramType = "query")
//            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query"),
//            @ApiImplicitParam(name = "pageSize", value = "一页多少条", dataType = "Integer", paramType = "query")
//    })
// @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize
    @GetMapping
    public ResponseEntity<?> getDeptByDname(@RequestParam(value = "dname") String dname) {
        if (!dname.equals("") && !dname.isEmpty()) {
            List<Dept> dept = null;
            try {
//                String orderBy = "CreateTime DESC";
//                PageHelper.startPage(pageNum, pageSize, orderBy);
                dept = service.getDeptByDname(URLDecoder.decode(dname, "utf-8"));
//                record = new PageInfo<>(dept);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpStatus status = HttpStatus.OK;
            return new ResponseEntity<List<Dept>>(dept, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "院系名称不能为空 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="新增院系信息",notes="新增院系信息,院系编号不允许重复",produces = "application/json")
    @PostMapping
    public ResponseEntity<?> addDept(@Valid @RequestBody Dept record, BindingResult bindingResult) {
        record.setCreatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getDeptByOneDid(record.getDid());

            if (!findOne.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的院系编号" + record.getDid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service.addDept(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                    JsonResult jsonResult = new JsonResult(ResultStatus.ADD_DATA_ERROR, "Add Dept Data is Error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }

    @ApiOperation(value="删除院系",notes="根据 url 的 id 来删除院系",produces = "application/json")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delDeptById(@PathVariable(value = "id") Integer id) {
        if (!id.equals(0)) {
            int result = service.deleteDeptById(id);
            if (result >= 0) {
                HttpStatus status = HttpStatus.OK;
                JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                return new ResponseEntity<JsonResult>(jsonResult, status);
            } else {
                HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                JsonResult jsonResult = new JsonResult(ResultStatus.DELETE_DATA_ERROR, "Delete Dept Data is Error, the id is" + id + " !!!");
                return new ResponseEntity<JsonResult>(jsonResult, status);
            }
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(result, status);
        }
    }

    @ApiOperation(value="修改院系信息",notes="修改院系信息,院系编号不允许重复",produces = "application/json")
    @PutMapping
    public ResponseEntity<?> putDept(@Valid @RequestBody Dept record, BindingResult bindingResult) {
        record.setUpdatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getDeptByOneDid(record.getDid());

            if (!findOne.equals(1)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的院系编号" + record.getDid() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service.putDept(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult jsonResult = new JsonResult(ResultStatus.UPDATE_DATA_ERROR, "Update Dept is error");
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }
}
